package com.sghy.xcxservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sghy.xcxservice.common.CustomException;
import com.sghy.xcxservice.common.Error;
import com.sghy.xcxservice.dto.UserInfoVo;
import com.sghy.xcxservice.entity.BgbOrgUser;
import com.sghy.xcxservice.service.BgbOrgUserService;
import com.sghy.xcxservice.mapper.BgbOrgUserMapper;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.sghy.xcxservice.common.TokenInterceptor.getUid;

/**
* @author pc
* @description 针对表【bgb_org_user(机构子账号表)】的数据库操作Service实现
* @createDate 2025-05-29 18:10:16
*/
@Service
public class BgbOrgUserServiceImpl extends ServiceImpl<BgbOrgUserMapper, BgbOrgUser>
    implements BgbOrgUserService{
    
    @Override
    public BgbOrgUser getByUid(String uId) {
        QueryWrapper<BgbOrgUser> wrapper = new QueryWrapper<>();
        wrapper.eq("u_id",uId);
        return baseMapper.selectOne(wrapper);
    }
    
    @Override
    public UserInfoVo getUserInfo(String uId) {
        return baseMapper.getUserInfo(uId);
    }
    
    @Override
    public UserInfoVo getUserInfo() {
        return baseMapper.getUserInfo(getUid());
    }
    
    /**
     * 查询所有的用户列表，返回List<UserInfoVo>,还需要每个人打卡的总记录数量
     */
    @Override
    public List<UserInfoVo> getAllUserList(int page, int size) {
        return baseMapper.getAllUserList((page-1)*size, size);

    }
    
    @Override
    public List<UserInfoVo> getAllAdminList(int page, int size) {
        return baseMapper.getAllAdminList((page-1)*size, size);
    }
    
    @Override
    public List<UserInfoVo> searchUser(String like) {
        return baseMapper.searchUser(like);
    }
    
    @Override
    public void setAdmin(String uId) {
        BgbOrgUser user = getByUid(uId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        user.setAdmin(1);
        baseMapper.updateById(user);
        
    }
    
    @Override
    public void cancelAdmin(String uId) {
        BgbOrgUser user = getByUid(uId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        if (user.getAdmin() == 0) {
            throw new RuntimeException("该用户不是管理员，无法取消");
        }
        user.setAdmin(0);
        baseMapper.updateById(user);
        
    }
    
    @Override
    public void savaUserHeadIco(String uid, String headIco) {
        BgbOrgUser user = getByUid(uid);
        if (user == null) {
            throw new CustomException(Error.NO_USER,"用户不存在");
        }
        user.setHeadIco(headIco);
        baseMapper.updateById(user);
    }
    
}




